<template>
    <el-form :model="form" ref="formRef">
        <el-form-item label="用户名：" prop="username" :rules="[{required: true,message:'请输入用户名'}]">
            <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" :rules="[{required: true,message:'请输入密码'}]">
            <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="name" :rules="[{required: true,message:'请输入姓名'}]">
            <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item lable="角色" prop="role" :rules="[{required: true,message:'请选择角色'}]">
            <el-radio-group v-model="form.role">
                <el-radio label="student">学生</el-radio>
                <el-radio label="teacher">教师</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.role === 'student'" label="年龄：" prop="age" :rules="[{required: true,message:'请输入年龄'}]">
            <el-input v-model="form.age" type="number"></el-input>
        </el-form-item>
        <el-form-item v-if="form.role === 'student'" label="专业：" prop="major" :rules="[{required: true,message:'请输入专业'}]">
            <el-input v-model="form.major"></el-input>
        </el-form-item>
        <el-form-item >
            <el-button type="primary" @click="onSubmit">注册</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref } from 'vue'
import { useMemberStore } from '../stores/member'
import { useRouter } from 'vue-router';
import { ElMessage} from 'element-plus'

const form =ref({
    username: '',
    password: '',
    role: 'student',
    name: '',
    age:null,
    major: ''
})

const formRef = ref(null)

const router = useRouter()
const memberStore = useMemberStore()

const onSubmit = ()=> {
    formRef.value.validate((valid) => {
        if(valid){
            const existingUser = memberStore.getUserByUsername(form.value.username)
            if(existingUser){
                ElMessage.error('用户名已存在')
            }else{
                memberStore.addUser({...form.value})
                ElMessage.success('注册成功')
                router.replace('/login')
            }
        }
    })
}

const cancel = () =>{
    router.push('/')
}
</script>